package bounjour.ui;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bounjour.User;

import java.io.*;
import java.util.ArrayList;


/**
 * Servlet implementation class Login
 */
public class Register extends BaseServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Register() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		map.put("title", "Register");
		map.put("message", "");
		process(request, response, "register.ftl", false);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String displayName = request.getParameter("displayName").trim();
		String userEmail = request.getParameter("userEmail").trim();
		String userPassword = request.getParameter("userPassword").trim();
		String userPassword2 = request.getParameter("userPassword2").trim();
		
		ArrayList <String> resultList = new ArrayList<String>();
		resultList = User.register(displayName, userEmail, userPassword, userPassword2);
		
		if (resultList.size() == 0) {
		User user = new User();
		user.setDisplayName(displayName);
		user.setEmail(userEmail);
		user.save(userPassword);
		HttpSession session = request.getSession();
		session.setAttribute("user", user);
		response.sendRedirect("Home");
		}else{
			map.put("title", "Login");
			String errStr ="";
			 for (String err : resultList){
				 errStr += "<p class=\"failureNotification\">"+ err +"</p>";
			 }
			map.put("message", errStr);
			process(request, response, "register.ftl", false);
		}		
	}
	
	

}

